import router from './router'
import store from './store'
// eslint-disable-next-line no-unused-vars
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/framework/utils/auth' // get token from cookie
import getPageTitle from '@/framework/utils/get-page-title'
import {
  dealRouter,
  dealSingleSignOn,
  dealssoLogin
} from '@/framework/utils/menu'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = [
  '/login',
  '/authentication',
  '/newForgetPw',
  '/forceUpdatePw',
  '/submitOrder',
  '/binaryTree',
  '/mall/refund',
  '/mall/container',
  '/mall/product',
  '/mall/register',
  '/classroomLogin',
  '/classroomRegister',
  '/monitorPlay/playDownView',
  '/onlineClassroom/home',
  '/instantMessaging/tourist'
] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken && hasTokenToNext(to, from, next)) {
    await dealRoles(to, from, next)
  } else {
    notTokenToNext(to, from, next)
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

async function dealRoles(to, from, next) {
  // roles保存在vuex里，刷新就没了，需要重新调'user/getInfo'查
  const hasRoles = store.getters.roles && store.getters.roles.length > 0
  // 不能根据角色判断是否查询了
  if (hasRoles) {
    // 点击浏览器返回时    处理查询菜单逻辑
    if (
      to.meta.appCode !== from.meta.appCode &&
      to.meta.appCode &&
      from.fullPath !== '/'
    ) {
      // appCode（应用）不同且不是门户首页
      store.dispatch('permission/dealBackGenerateRoutes', {
        currentPath: to.path
      }) // 为了查新应用的菜单
    }
    to.path === '/undefined' ? next({ path: '/' }) : next()
  } else {
    // 没有token令牌时，或者token失效
    try {
      // get user info
      // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']

      // router.options.routes = accessRoutes
      // hack method to ensure that addRoutes is complete
      // set the replace: true, so the navigation will not leave a history record
      const { roles } = await store.dispatch('user/getInfo')
      await dealRouter(to.path, roles)
      next({ ...to, replace: true })
    } catch (error) {
      // remove token and go to login page to re-login
      await store.dispatch('user/resetToken')
      // Message.error(error || 'Has Error')
      if (to.path.indexOf('onlineClassroom') !== -1) { // 线上课堂登录过期前往线上课堂登录页面
        next(`/classroomLogin?redirect=${to.path}`)
        return
      }
      next(`/login?redirect=${to.path}`)
      NProgress.done()

      // await dealRouter(to.path, roles)
      // next({ ...to, replace: true })
    }
  }
}

function hasTokenToNext(to, from, next) {
  const isLock = localStorage.getItem('isLock')
  // 单点登录
  if (to.query.ssoLoginFlag == 'true') {
    dealssoLogin(to)
  } else if (isLock && to.path !== '/lock') {
    // 锁屏
    next({
      path: `/lock?redirect=${from.query.redirect}`
    })
    NProgress.done()
  } else if (to.path === '/login') {
    // 直接登录
    next({ path: '/' })
    NProgress.done()
  } else {
    return true
  }
}

function notTokenToNext(to, from, next) {
  if (whiteList.indexOf(to.path) !== -1) {
    // 白名单
    dealSingleSignOn(to, from, next)
  } else {
    // dealSingleSignOn(to, from, next)
    if (to.path.indexOf('onlineClassroom') !== -1) { // 线上课堂登录过期前往线上课堂登录页面
      next(`/classroomLogin?redirect=${to.path}`)
      return
    }
    to.path === '/logout' ? next('/login') : next(`/login?redirect=${to.path}`)
    NProgress.done()
  }
}
